package BandB.Tool.GPhoneManager.TaskManager;

import java.util.ArrayList;
import java.util.List;

import BandB.Tool.GPhoneManager.R;
import BandB.Tool.GPhoneManager.TaskManager.Util.Utilities;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * GridView adapter to show the list of applications and shortcuts
 * 
 * @author gjbie
 */
public class ApplicationsAdapter extends ArrayAdapter<ApplicationInfo> {
	private final LayoutInflater mInflater;
	private final List<ApplicationInfo> mAppsList;

	/**
	 * Constructor for this adapter
	 * 
	 * @param context
	 *            {@link Context} object
	 * @param apps
	 *            {@link ArrayList} object
	 * @see ArrayList
	 */
	public ApplicationsAdapter(final Context context,
			final ArrayList<ApplicationInfo> apps) {
		super(context, 0, apps);
		mAppsList = apps;
		mInflater = LayoutInflater.from(context);
	}

	/**
	 * Get a list of {@link ApplicationInfo} objects
	 * 
	 * @return {@link ApplicationInfo} list
	 */
	public final List<ApplicationInfo> getMAppsList() {
		return mAppsList;
	}

	/**
	 * Get a View that displays the data at the specified position in the data
	 * set.
	 * 
	 * @param position
	 *            Specified position
	 * @param view
	 *            The old view to reuse, if possible
	 * @param parent
	 *            The parent that this view will eventually be attached to
	 * @return return view at the specified position
	 */
	@Override
	public final View getView(final int position, final View view,
			final ViewGroup parent) {
		final ApplicationInfo info = getItem(position);

		View convertView = view;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.task_list_item, parent,
					false);
		}

		if (!info.filtered) {
			info.icon = Utilities.createIconThumbnail(info.icon, getContext());
			info.filtered = true;
		}
		convertView.setTag(info);
		final ImageView iconImage = (ImageView) convertView
				.findViewById(R.id.task_icon);
		iconImage.setBackgroundDrawable(info.icon);
		final TextView appTextView = (TextView) convertView
				.findViewById(R.id.task_name);
		appTextView.setText(info.title);
		final CheckBox checkBox = (CheckBox) convertView
				.findViewById(R.id.task_check);
		checkBox.setChecked(info.isCheck);
		return convertView;
	}

	/**
	 * Set item checked at the specified position
	 * 
	 * @param position
	 *            position specified
	 */
	public final void setCheckAt(final int position) {

		getItem(position).setCheck(!getItem(position).isCheck);
		notifyDataSetChanged();
	}

}
